// pages/sharePage/sharePage.js
var app = getApp();
Page({
  /**
   * 页面的初始数据
   */
  data: { // mark: pagedata
    centerY: 30.302915,
    centerX: 120.081699,

    mapShow: false,
    content: '', //文字内容
    imgs: [], //图片
    tmp_imgs: [], //缓存页面图片
    cloud_imgs: [],
    tags: [],
    position: '',
    user: {
      name: 'Uname',
      user_id: '1234556',
      user_photo: 'Uimg',
    }, //用户信息
    location: {
      longitude: '',
      latitude: ''
    },
    animalList: [{
        name: '知识雪豹',
        id: 1,
      },
      {
        name: '2号',
        id: 2,
      }
    ],
    animal: '',
    animal_id: '',
    animal_data: {},
    markers: [{
      id: 0,
      latitude: 30.302915,
      longitude: 120.081699,
      width: 30,
      height: 40,
    }]
  },
  //分享内容缓存
  contentInput: function (e) {
    this.setData({
      content: e.detail.value,
    })
    wx.setStorage({
      key: "postContent",
      data: this.data.content,
      success: function () {
        //console.log('设置缓存数据成功');
      }
    })
    //console.log(this.data.content)
  },
  //定位函数
  getPosition() {
    console.log("定位")
    var getpo = '123123';
    var that = this;
    this.setData({
      mapShow: true,
    })
    // wx.chooseLocation({
    //   success: function (res) {
    //     // success
    //     console.log(res, "location")
    //     that.setData({
    //       location: {
    //         longitude: res.longitude,
    //         latitude: res.latitude
    //       },
    //     })
    //     var lat = res.latitude;
    //     var lon = res.longitude;
    //     getpo = lat + ',' + lon;
    //     that.setData({
    //       position: getpo,
    //     })
    //     wx.setStorage({
    //       key: "postPosition",
    //       data: that.data.position,
    //       success: function () {
    //         //console.log('设置缓存数据成功');
    //       }
    //     })
    //   },
    //   fail: function () {
    //     console.log("fail")
    //   },
    // })
  },
  //发布按钮函数 mark:fabu
  handleShare: function () {
    let that = this;
    var animal_id = [];
    animal_id.push(this.data.animal_id);
    // console.log(this.data.animal_id)
    if (this.data.content != '' && this.data.position != '' && this.data.imgs.length != 0 && this.data.animal_id != '') {
      var db_img = []; //存放数据库图片路径
      Promise.all( //异步操作确保完成
        that.data.imgs.map((item) => { //每个item是图片临时地址
          return new Promise((resolve, reject) => {
            wx.uploadFile({
              url: 'https://api.fracher21.top/spotit-static/upload', // 后端接口地址
              filePath: item,
              name: 'image', // !!注意
              formData: {
                'category': 'post' // 可选：test（测试用）, head（用户头像）, post（帖子图片），animal（动物头像），common（通用，如默认头像），写其他的会上传失败并返回错误信息
              },
              success: function (res) {
                // 获取后端返回的图片URL
                var url = JSON.parse(res.data).url;
                resolve(url);
              }
            })
          })
        })
      ).then((result) => {
        db_img = result;
        console.log(db_img)
        wx.request({
          url: 'https://api.fracher21.top/spotit/createpost',
          method: "POST",
          data: {
            token: app.globalData.token,
            body: that.data.content, // 帖子正文
            x: that.data.location.longitude,
            y: that.data.location.latitude, // 位置经纬度
            images: db_img,
            animals: animal_id // 需要已经存在的anmial id，在现实中应该通过选择已有动物获得
          },
          success: (res) => {
            // console.log(res.data)
            that.setData({
              content: '',
              imgs: [],
              tmp_imgs: [],
              position: '',
              animal: '',
              animal_id: '',
              animal_data: {},
            })
            wx.setStorage({
              key: "postContent",
              data: '',
            })
            wx.setStorage({
              key: "postPosition",
              data: '',
            })
            wx.setStorage({
              key: "animalHuancun",
              data: {},
            })
            wx.setStorageSync('imgHuancun', '');
            wx.showToast({
              title: "发布成功",
              icon: "success",
              duration: 3000,
              mask: false,
            })
          }
        })
      })
    } else if (this.data.content != '' && this.data.position != '' && this.data.animal_id != '') {
      wx.showModal({
        title: '提示',
        content: '您还未提供照片，确定要上传吗？',
        complete: (res) => {
          if (res.cancel) {
            return;
          }
          if (res.confirm) {
            wx.request({
              url: 'https://api.fracher21.top/spotit/createpost',
              method: "POST",
              data: {
                token: app.globalData.token,
                body: that.data.content, // 帖子正文
                x: that.data.location.longitude,
                y: that.data.location.latitude, // 位置经纬度
                images: db_img,
                animals: animal_id // 需要已经存在的anmial id，在现实中应该通过选择已有动物获得
              },
              success: (res) => {
                // console.log(res.data)
                that.setData({
                  content: '',
                  imgs: [],
                  tmp_imgs: [],
                  position: '',
                  animal: '',
                  animal_id: '',
                  animal_data: {},
                })
                wx.setStorage({
                  key: "postContent",
                  data: '',
                })
                wx.setStorage({
                  key: "postPosition",
                  data: '',
                })
                wx.setStorage({
                  key: "animalHuancun",
                  data: {},
                })
                wx.setStorageSync('imgHuancun', '');
                wx.showToast({
                  title: "发布成功",
                  icon: "success",
                  duration: 3000,
                  mask: false,
                })
              }
            })
          }
        }
      })
    } else {
      wx.showToast({
        title: "发布信息不完善",
        icon: "error",
        duration: 3000,
        mask: false,
      })
    }
  },
  chooseImage() { // mark: 图片相关
    var that = this;
    var imgs = this.data.imgs;
    var tempo1 = 9 - imgs.length
    if (tempo1 <= 0) {
      wx.showToast({
        title: '最多添加九张',
        icon: 'none',
        duration: 2000,
      })
    } else {
      wx.chooseMedia({
        count: 9,
        mediaType: ['image'],
        sizeType: ['compressed'],
        sourceType: ['album', 'camera'],
        camera: 'back',
        success(res) {
          console.log(res) //上传的图片数组
          var tempFiles = res.tempFiles;
          var imgs = that.data.imgs;
          // console.log(imgs)
          var tmp_imgs = that.data.tmp_imgs;
          for (var i = 0; i < tempFiles.length; i++) {
            if (imgs.length >= 9) {
              that.setData({
                imgs: imgs,
                tmp_imgs: tmp_imgs,
              });
              return false;
            } else {
              imgs.push(tempFiles[i].tempFilePath);
              tmp_imgs.push(tempFiles[i].tempFilePath);
            }
          }
          that.setData({
            imgs: imgs,
            tmp_imgs: tmp_imgs,
          });
          //console.log(res.tempFiles.length)
          wx.setStorageSync('imgHuancun', that.data.tmp_imgs);
        },
        fail(res) {
          console.log("uploadfail")
        }
      })
    }
  },
  deleteImg: function (e) {
    // console.log(e.currentTarget.dataset.index)
    var that = this;
    var index = e.currentTarget.dataset.index;
    var imgs = that.data.imgs;
    wx.showModal({
      title: '提示',
      content: '确定要删除此图片吗？',
      success: function (res) {
        if (res.confirm) {
          console.log('点击确定');
          imgs.splice(index, 1);
        } else if (res.cancel) {
          console.log('点击取消');
          return false;
        }
        that.setData({
          imgs: imgs,
        })
        wx.setStorageSync('imgHuancun', imgs);
      },
      fail(res) {
        console.log('del fail')
      }
    })
  },
  //以下为弹窗内容 // mark: 筛选弹窗
  showDialogBtn: function () {
    this.setData({
      showModal: true
    })
    this.getAnimalList();
  },
  preventTouchMove: function () {},
  onCancel: function () {
    var animal = this.data.animal;
    this.setData({
      showModal: false,
      animal: animal,
    });
  },
  onConfirm: function () {
    let that = this;
    if (this.data.animal == '') {
      wx.showToast({
        title: "还未作出选择哦",
        icon: "error",
        duration: 3000,
        mask: false,
      })
    } else {
      wx.request({
        url: 'https://api.fracher21.top/spotit/animalinfo',
        method: "GET",
        data: {
          id: that.data.animal_id, // 动物的id，实际情况应该是通过别的请求获得的（如某一用户创建的动物列表，地图钉点击，帖子关联的动物等
        },
        success: (res) => {
          that.setData({
            animal_data: res.data,
          })
          console.log(that.data.animal_data)
          var animal_huancun = {
            animal_data: that.data.animal_data,
            animal: that.data.animal,
            id: that.data.animal_id
          };
          wx.setStorage({
            key: "animalHuancun",
            data: animal_huancun,
          })
        }
      })
      this.setData({
        showModal: false
      });
    }
  },
  //mark: 动物
  getAnimalList() { //获取已有动物列表 ,并赋给页面
    let that = this;
    wx.request({
      url: 'https://api.fracher21.top/spotit/listanimals',
      method: 'GET',
      data: {
        token: app.globalData.token,
      },
      success(res) {
        //  console.log(res.data.data)
        that.setData({
          animalList: res.data.data,
        })
      }
    })
  },
  //获取选择的动物
  getAnimal(e) {
    if ((e.currentTarget.dataset.id == this.data.animal_id) && (this.data.animal_id != '')) {
      this.setData({
        animal: '',
        animal_id: ''
      })
    } else {
      this.setData({
        animal: e.currentTarget.dataset.animal,
        animal_id: e.currentTarget.dataset.id
      })
    }
  },
  //前往添加新的动物（带名字的个体）
  addAnimal() {
    console.log("add animal!")
    var name = this.data.user.name;
    var id = this.data.user.user_id;
    wx.navigateTo({
      url: '/pages/addAnimal/addAnimal?user_name=' + name + '&user_id=' + id,
    })
  },
  /**
   * 生命周期函数--监听页面加载
   */
  onLoad(options) { // mark: zhouqi
    let pageThis = this; //拿到page的“指针”
    wx.request({ //获取当前用户数据
      url: 'https://api.fracher21.top/spotit/getuserinfo',
      method: "GET",
      data: {
        token: app.globalData.token // 不要忘了这个
      },
      success: (res) => {
        // console.log(res.data)
        pageThis.setData({
          ['user.name']: res.data.name,
          ['user.user_id']: res.data.id, //res.data.id
        })
        // 用户名：res.data.name
        // 头像：res.data.head
        // 签名：res.data.motto
      },
      fail: (res) => {
        console.log('fail')
      }
    })
    this.getAnimalList();
    wx.getStorage({
      key: 'postContent', //从缓存里面拿出编辑的post内容
      success(res) {
        //console.log(res.data)
        pageThis.setData({
          content: res.data,
        })
      }
    })
    wx.getStorage({
      key: 'postPosition',
      success(res) {
        pageThis.setData({
          position: res.data,
        })
      }
    })
    wx.getStorage({
      key: 'postLocation',
      success(res) {
        pageThis.setData({
          location: res.data,
        })
      }
    })
    wx.getStorage({
      key: 'animalHuancun',
      success(res) {
        //console.log(res)
        pageThis.setData({
          animal_data: res.data.animal_data,
          animal: res.data.animal,
          animal_id: res.data.id,
        })
      }
    })
    //console.log(this.data.imgs)
    var imgShow = wx.getStorageSync('imgHuancun');
    if (imgShow) {
      this.setData({
        imgs: imgShow,
      })
    } else {
      this.setData({
        imgs: [],
      })
    }
  },
  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  mapclick: function (e) { //mark:map
    var that = this;
    console.log("地图点击", e.detail);
    var lat = e.detail.latitude;
    var lon = e.detail.longitude;
    var location = {
      longitude: lon,
      latitude: lat
    };
    this.setData({
      ['markers[0].latitude']: lat,
      ['markers[0].longitude']: lon,
      location: location,
    })
    var l1 = lat.toFixed(3);
    var l2 = lon.toFixed(3)
    var getpo = l1 + ',' + l2;
    that.setData({
      position: getpo,
    })
    console.log(that.data.location)
    wx.setStorage({
      key: "postPosition",
      data: that.data.position,
      success: function () {
        //console.log('设置缓存数据成功');
      }
    })
    wx.setStorage({
      key: "postLocation",
      data: that.data.location,
      success: function () {
        //console.log('设置缓存数据成功');
      }
    })
  },
  mapBack() {
    this.setData({
      mapShow: false,
    })
  },
  onReady() {
    this.mapCtx = wx.createMapContext('map')
  },
  /**
   * 生命周期函数--监听页面显示
   */
  onShow() {
    console.log('show')
  },
  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide() {

  },
  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload() {
    // console.log('缓存数据')
  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh() {

  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom() {

  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage() {

  }
})